﻿using System;
using MySql.Simple.Mapper.Finders;
using MySql.Simple.Mapper.Readers;
using MySql.Simple.Mapper.Structures;

namespace MySql.Simple.Mapper.Commands.Tables
{
    /// <summary>
    /// Writes the contents of the given object into the database.
    /// </summary>
    public static class ExistsCommand
    {
        private const string Sql = @"SHOW TABLES;";

        public static bool Execute(string tableName, Connection connection)
        {
            var exists = false;

            var tables = StringReader.Read(Sql, connection);

            foreach (var table in tables)
            {
                if (string.Compare(table, tableName, true) != 0) continue;

                exists = true;

                break;
            }

            return exists;
        }

        public static bool Execute(Type type, Connection connection)
        {
            var tableName = TableNameFinder.Find(type);

            return Execute(tableName, connection);
        }
        
        public static bool Execute<T>(Connection connection) 
        {
            return Execute(typeof (T), connection);
        }
    }
}